﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VERKProjectHopur16.Models;
using VERKProjectHopur16.Helpers;
using System.Configuration;
using System.Net.Mail;
using System.IO;
using System.Text;


namespace VERKProjectHopur16.Controllers
{
    /// <summary>
    /// Controller for frontpage and not loggedIn functionality in system
    /// </summary>
    [HandleError]
    public class HomeController : ParentController
    {
        IDataRepository m_rep = null;

        public HomeController()
        {
            m_rep = new DataRepository();
        }

        public HomeController(IDataRepository rep)
        {
            m_rep = rep;
        }

        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome IRIS";
            const int ALL_LANGUAGES = 4;
            int lang = ALL_LANGUAGES;
            String strSort = "InsertDate";

            if (Session["langFront"] != null)
            {
                Int32.TryParse(Session["langFront"].ToString(), out lang);
            }

            var tempResult = (from content in m_rep.GetAllContent()
                              where content.Active == true
                              select content);

            if (lang != ALL_LANGUAGES)
            {
                tempResult = tempResult.Where(m => m.LanguageID == lang);
            }

            //top content ans news for all departments
            TopContentViewModel topAllDept = new TopContentViewModel();
            topAllDept.topNews = tempResult.Where(m => m.CategoryID == 1).Take(5).AsQueryable().OrderByDescending(strSort);
            topAllDept.TopContent = tempResult.Where(m => m.CategoryID != 1).Take(4).AsQueryable().OrderByDescending(strSort);

            //top content ans news for medicine department
            TopContentViewModel topMedDept = new TopContentViewModel();
            topMedDept.topNews = tempResult.Where(m => m.CategoryID == 1 && m.DepartmentID == 2).Take(5).AsQueryable().OrderByDescending(strSort);
            topMedDept.TopContent = tempResult.Where(m => m.CategoryID != 1 && m.DepartmentID == 2).Take(4).AsQueryable().OrderByDescending(strSort);

            //top content ans news for psychology departments
            TopContentViewModel topPsyDept = new TopContentViewModel();
            topPsyDept.topNews = tempResult.Where(m => m.CategoryID == 1 && m.DepartmentID == 3).Take(5).AsQueryable().OrderByDescending(strSort);
            topPsyDept.TopContent = tempResult.Where(m => m.CategoryID != 1 && m.DepartmentID == 3).Take(4).AsQueryable().OrderByDescending(strSort);

            //top content ans news for sociology departments
            TopContentViewModel topSocDept = new TopContentViewModel();
            topSocDept.topNews = tempResult.Where(m => m.CategoryID == 1 && m.DepartmentID == 4).Take(5).AsQueryable().OrderByDescending(strSort);
            topSocDept.TopContent = tempResult.Where(m => m.CategoryID != 1 && m.DepartmentID == 4).Take(4).AsQueryable().OrderByDescending(strSort);

            TopDepViewModel model = new TopDepViewModel();
            model.topAllContent = topAllDept;
            model.topMedContent = topMedDept;
            model.topPsyContent = topPsyDept;
            model.topSocContent = topSocDept;
            return View(model);
        }
        /// <summary>
        /// Helper function for language selection
        /// </summary>
        public ActionResult LanguageFront(int? id)
        {
            if ( id.HasValue )
            {
                Session["langFront"] = id;
            }
            return RedirectToAction("Index");
        }

        public ActionResult SingleContent(int? id)
        {
            if ( id.HasValue )
            {
                var real_id = id.Value;
                var result = m_rep.GetContentById(real_id);
                if ( result == null )
                {
                    return View("NotFound");
                }
                return View(result);
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult SingleEvent(int? id)
        {
            if ( id.HasValue )
            {
                var event_id = id.Value;
                var result = m_rep.GetEventById(event_id);
                if ( result == null ) 
                {
                    return View("NotFound");
                }
                return View(result);
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult SingleQA(int? id)
        {
            if ( id.HasValue )
            {
                var Q_A_id = id.Value;
                var result = m_rep.GetQAById(Q_A_id);
                if ( result == null )
                {
                    return View("NotFound");
                }
                return View(result);
            }
            else
            {
                return View("NotFound");
            }
        }

        /// <summary>
        /// Helpers function for language selection
        /// </summary>
        public ActionResult SiteLang(string lang)
        {
            //TODO: Move to Web.Config
            List<string> LangList = new List<string>();
            LangList.Add("en");
            LangList.Add("is");
            LangList.Add("se");

            if( LangList.Contains(lang) )
            {
                Session["site-lang"] = lang;
            }

            if (Request.UrlReferrer.ToString() != null)
            {
                Response.Redirect(Request.UrlReferrer.AbsoluteUri);
            }
            else
            { 
                Response.Redirect("/");
            }
            return View("NotFound");
        }
    
        public ActionResult About()
        {
            return View();
        }

        public ActionResult Donate()
        {
            return View();
        }

        public ActionResult Postlist()
        {
            return View();
        }

        public ActionResult AllChildren()
        { 
            var model = from item in m_rep.AllChilds()
                        where item.Active == true
                        select item;

            return View(model);
        }

        [HttpGet]
        public ActionResult RequestTimeline(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                TimelineRequestModel model = new TimelineRequestModel();
                model.ChildID = realID;
                return View(model);
            }
            else
            {
                return View("NotFound");
            }
        }

        [HttpPost]
        public ActionResult RequestTimeline(TimelineRequestModel model)
        {
            if ( ModelState.IsValid )
            {
                var child = m_rep.GetChildById(model.ChildID);

                if (model.Password != child.ProfilePassword)
                {
                    ModelState.AddModelError("", "Incorrect Password");
                }
                else
                { 
                    return RedirectToAction("Timeline", new { id = model.ChildID });
                }
            }
            return View(model);
        }

        /// <summary>
        /// Get all the pictures belonging to the specified child(id)
        /// </summary>
        public ActionResult Timeline(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = from item in m_rep.AllPictures()
                            where item.ChildID == realID
                            orderby item.PictureDate
                            select item;
                return View(model);
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult PasswordRequest(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;

                PasswordRequestViewModel model = new PasswordRequestViewModel();
                model.ChildID = realID;

                return View(model);
            }
            else
            {
                return View("NotFound");
            }
        }

        /// <summary>
        /// Sends email to child creator requestion password to access the timeline in question
        /// </summary>
        [HttpPost]
        public ActionResult PasswordRequest(PasswordRequestViewModel model)
        {
            if (ModelState.IsValid)
            {
                string email = (from item in m_rep.AllChilds()
                                where item.ChildID == model.ChildID
                                select item.aspnet_Membership.Email).SingleOrDefault();
                string childName = (from item in m_rep.AllChilds()
                                   where item.ChildID == model.ChildID
                                   select item.Name).SingleOrDefault();
                if (email == null && childName == null)
                {
                    return View("NotFound");
                }
                else
                { 
                    try
                    {
                        string strEmail = email;
                        string srtSuject = ConfigurationManager.AppSettings["PasswordRequest"];
                        using (MailMessage the_message = new MailMessage())
                        {
                            the_message.To.Add(strEmail);
                            the_message.Subject = srtSuject;
                            the_message.Body = model.Name + " has requested the password for " + childName + ". " + model.Name + " email is " + model.Email + ".";
                            SmtpClient client = new SmtpClient();
                            client.EnableSsl = true;
                            client.Send(the_message);
                        }
                    }
                    catch (Exception ex)
                    {
                        String LogFilePath = HttpContext.Server.MapPath(ConfigurationManager.AppSettings["LogFile"]);
                        String strPath = Path.GetDirectoryName(LogFilePath);
                        if (!Directory.Exists(strPath))
                        {
                            Directory.CreateDirectory(strPath);
                        }
                        using (StreamWriter writer = new StreamWriter(LogFilePath, true, Encoding.Default))
                        {
                            writer.WriteLine(string.Format("Could not send email notification.For: {1}{2}", ex.Source, ex.StackTrace));
                        }
                    }
                }
                    return RedirectToAction("AllChildren");
            }
            return View(model);
        }
    }
}
